package hydrap2p.library;

import hydrap2p.ServiceLocation;

import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;

public class MetadaterCollection {

	private Map<String, Map<ServiceLocation,Metadater>> metadaters;
	
	public MetadaterCollection()
	{
		metadaters=new TreeMap<String, Map<ServiceLocation,Metadater>>();
	}
	
	public void put(String extension, ServiceLocation location, Metadater metadater)
	{
		Map<ServiceLocation,Metadater> inner;
		extension=extension.toLowerCase();
		synchronized(metadaters)
		{
			if (metadaters.keySet().contains(extension))
				inner=metadaters.get(extension);
			else
			{
				inner=new TreeMap<ServiceLocation,Metadater>();
				metadaters.put(extension, inner);
			}
		}
		
		synchronized(inner)
		{
			inner.put(location, metadater);
		}
	}
	
	public void remove(String extension, ServiceLocation location)
	{
		Map<ServiceLocation,Metadater> inner=null;
		extension=extension.toLowerCase();
		synchronized(metadaters)
		{
			if (metadaters.keySet().contains(extension))
				inner=metadaters.get(extension);
			if (inner!=null)
			{
				synchronized(inner)
				{
					inner.remove(location);
					if (inner.isEmpty())
						metadaters.remove(extension);
						
				}
			}
		}
	}
	
	public void removeAll(String extension, Collection<ServiceLocation> locations)
	{
		Map<ServiceLocation,Metadater> inner=null;
		extension=extension.toLowerCase();
		synchronized(metadaters)
		{
			if (metadaters.keySet().contains(extension))
				inner=metadaters.get(extension);
			if (inner!=null)
			{
				synchronized(inner)
				{
					inner.keySet().removeAll(locations);
					if (inner.isEmpty())
						metadaters.remove(extension);
						
				}
			}
		}
	}
	
	public synchronized Map<ServiceLocation,Metadater> getList(String extension)
	{
		Map<ServiceLocation,Metadater> ret=new TreeMap<ServiceLocation,Metadater>();
		if (metadaters.containsKey(extension))
			ret.putAll(metadaters.get(extension));
		if (metadaters.containsKey("*"))
			ret.putAll(metadaters.get("*"));
		return ret;
	}
}
